Param(
	[string]$Configuration = "Release",
	[string]$Runtime = "win-x64",
	[string]$AppVersion = "1.0.0",
	[string]$InnoSetup = "C:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe",
	[switch]$SingleFile
)

$ErrorActionPreference = "Stop"

# 进入仓库根目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location (Join-Path $ScriptDir "..")

Write-Host "==> Publishing DBTools ($Configuration, $Runtime)"

$publishArgs = @(
	"publish", ".\DBTools\DBTools.csproj",
	"-c", $Configuration,
	"-r", $Runtime,
	"--self-contained", "true"
)

if ($SingleFile) {
	Write-Host "   - SingleFile: ON (IncludeNativeLibrariesForSelfExtract)"
	$publishArgs += "/p:PublishSingleFile=true"
	$publishArgs += "/p:IncludeNativeLibrariesForSelfExtract=true"
	$publishArgs += "/p:PublishTrimmed=false"
} else {
	Write-Host "   - SingleFile: OFF (recommended for native SQLite)"
	$publishArgs += "/p:PublishSingleFile=false"
}

& dotnet @publishArgs

$publishDir = Join-Path ".\DBTools\bin\$Configuration\net9.0-windows\$Runtime" "publish"
if (-not (Test-Path $publishDir)) {
	throw "Publish output not found: $publishDir"
}

Write-Host "   Output -> $publishDir"
Get-ChildItem -Path $publishDir | Select-Object Name, Length | Out-Host

Write-Host "==> Building installer via Inno Setup"

function Resolve-ISCC {
	param([string]$Preferred)
	$probes = @()
	if ($Preferred) { $probes += $Preferred }
	$probes += "C:\\Program Files\\Inno Setup 6\\ISCC.exe"
	$probes += "C:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe"
	foreach ($p in $probes) { if (Test-Path $p) { return $p } }
	try { $which = (Get-Command ISCC.exe -ErrorAction Stop).Source; if ($which) { return $which } } catch {}
	return $null
}

$ISCC = Resolve-ISCC -Preferred $InnoSetup
if (-not $ISCC) { throw "ISCC.exe not found. Please install Inno Setup 6 or specify -InnoSetup path." }

$env:AppVersion = $AppVersion
& "$ISCC" ".\Installer\DBTools.iss"

Write-Host "==> Done. Output: .\\installers"
